package com.bf.xpdd.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.bf.xpdd.domain.ActivityGlobal;
import com.bf.xpdd.domain.ActivitySettingBean;
import com.bf.xpdd.domain.SiteSeller;
import com.bf.xpdd.exception.BaseException;
import com.bf.xpdd.persistent.iface.DaoSeller;
import com.bf.xpdd.service.AccountService;
import com.bf.xpdd.service.TaobaoService;
import com.bf.xpdd.util.SettingUtility;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.taobao.api.domain.UserTag;

/**
 * account service implementation
 * @author Fantastic
 * @version 1.0.0 2011-06-25
 * @since 1.0.0
 */
@Component
public class AccountServiceImpl implements AccountService
{

	/** dao seller */
	@Autowired
	private DaoSeller daoSeller;
	
	/** ibatis session */
	@Autowired
	private SqlMapClient sqlMapClient;
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void addNewSeller(SiteSeller seller, TaobaoService taobaoService) throws BaseException
	{
		try
		{
			boolean result = this.daoSeller.querySellerIsExist(this.sqlMapClient, seller);
			if(!result)
			{
				//是否有人群标签，没有则创建
				List<UserTag> tagList;
				try 
				{
					tagList = taobaoService.findTagBySessionKey(seller.getTopSession());
					
					if(null != tagList && !tagList.isEmpty())
					{
						for(UserTag tag : tagList)
						{
							taobaoService.removeTag(seller.getTopSession(), tag.getTagId());
						}
					}
					
					tagList = new ArrayList<UserTag>(0);
					StringBuilder builder = new StringBuilder();
					for(int i = 0; i < 10; i++)
					{
						UserTag tag = taobaoService.addTag(seller.getTopSession(), seller.getNick() + "的标签" + i, seller.getNick() + "的标签描述" + i);
						if(null == tag)
						{
							continue;
						}
						tagList.add(tag);
						builder.append(tag.getTagId()).append(",");
					}
					//String tagStr = builder.substring(0, -1);
				}
				catch (BaseException e) 
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				this.sqlMapClient.startTransaction();
				long idSeller = this.daoSeller.insertNewSeller(this.sqlMapClient, seller);
				
				//创建用户同时开启一个活动
				ActivityGlobal global = new ActivityGlobal();
				Date date = new Date();
				global.setBeginTime(date);
				//默认所有淘宝用户均可参加、状态为运行中
				global.setRange(ActivityGlobal.RANGE_REGISTERED);
				global.setStatus(ActivityGlobal.STATUS_RUNNING);
				//编辑时间
				global.setEditTime(date);
				//用户本地编号
				global.setIdSeller(idSeller);
				global.setNick(seller.getNick());
				global.setNotice("欢迎使用血拼到底，祝您购物愉快。");
				
				//添加新的活动全局信息
				this.daoSeller.insertActivityGlobal(this.sqlMapClient, global);

				//添加个人模板
				ActivitySettingBean setting = SettingUtility.createDefaultSetting();
				setting.setNick(seller.getNick());
				setting.setName(seller.getNick() + "的默认模板");
				setting.setBaseLine(80);
				setting.setFirstDialogue("这样下去老板娘要跑了");
				setting.setSecondDialogue("想做善事，留给其他人吧");
				setting.setThridDialogue("我就狠一狠心");
				setting.setForthDialogue("给条活路吧!");
				this.daoSeller.insertActivitySetting(this.sqlMapClient, setting);

				this.sqlMapClient.commitTransaction();
				
			}
		} 
		catch (SQLException e)
		{
			throw new BaseException("新用户添加异常");
		}
		finally
		{
			try {
				this.sqlMapClient.endTransaction();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void persistSession(SiteSeller seller) throws BaseException
	{
		seller.setTimestamp(new Date());
		boolean isExist;
		try 
		{
			isExist = this.daoSeller.querySellerSessionKeyIsExist(sqlMapClient, seller);
			if(isExist)
			{
				this.daoSeller.updateSellerSessionKey(sqlMapClient, seller);
			}
			else
			{
				this.daoSeller.insertSellerSessionKey(sqlMapClient, seller);
			}
		} 
		catch (SQLException e) 
		{
			throw new BaseException("商家session异常");
		}

	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public List<SiteSeller> findAllSessionKey() throws BaseException
	{
		try
		{
			return this.daoSeller.queryAllSellerSessionKeyActive(sqlMapClient);
		} 
		catch (SQLException e)
		{
			e.printStackTrace();
			throw new BaseException("查询商家session异常");
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public SiteSeller findSessionKeyByNick(String nick) throws BaseException 
	{
		try
		{
			return this.daoSeller.querySessionKeyByNick(sqlMapClient, nick);
		} 
		catch (SQLException e)
		{
			throw new BaseException("查询商家session异常");
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void updateAccessTime(SiteSeller seller) throws BaseException
	{
		try 
		{
			seller.setTimestamp(new Date());
			this.daoSeller.updateSellerSessionKey(sqlMapClient, seller);
		} catch (SQLException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new BaseException("更新商家访问时间失败");
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void removeSessionKey(SiteSeller seller) throws BaseException
	{
		try 
		{
			this.daoSeller.deleteSellerSessionKeyByNick(this.sqlMapClient, seller);
		} 
		catch (SQLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new BaseException("-11", "删除用户sessionkey失败");
		}
		
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void removeAllSessionKey() throws BaseException 
	{
		try 
		{
			this.daoSeller.deleteAllSellerSessionKey(this.sqlMapClient);
		} 
		catch (SQLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new BaseException("-11", "删除用户sessionkey失败");
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void resetTagUser(SiteSeller seller, TaobaoService taobaoService) throws BaseException
	{
		//是否有人群标签，没有则创建
		List<UserTag> tagList;
		try 
		{
			tagList = taobaoService.findTagBySessionKey(seller.getTopSession());
			
			if(null != tagList && !tagList.isEmpty())
			{
				for(UserTag tag : tagList)
				{
					taobaoService.removeTag(seller.getTopSession(), tag.getTagId());
				}
			}
			
			tagList = new ArrayList<UserTag>(0);
			StringBuilder builder = new StringBuilder();
			for(int i = 0; i < 10; i++)
			{
				UserTag tag = taobaoService.addTag(seller.getTopSession(), seller.getNick() + "的标签" + i, seller.getNick() + "的标签描述" + i);
				if(null == tag)
				{
					continue;
				}
				tagList.add(tag);
				builder.append(tag.getTagId()).append(",");
			}
			//String tagStr = builder.substring(0, -1);
		}
		catch (BaseException e)
		{
			throw new BaseException("重置标签用户失败");
		}
	}

}
